package com.design.composite.utils;

import com.design.composite.entity.Records;
import com.design.composite.repository.DictRepository;
import com.design.composite.repository.RecordsRepository;
import com.design.composite.web.param.GenerateMaterialParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.*;

/**
 * @author liuyajun
 */
@Component
public class PicUtil {
    @Autowired
    private RecordsRepository recordsRepository;
    @Autowired
    private DictRepository dictRepository;

    //@Async
    public void generateBufferImages(Map<Integer, List<GenerateMaterialParam>> map, Integer index, List<GenerateMaterialParam> compositeList, String savePath, String code) throws IOException {
        String materialPrePath = dictRepository.findByCode("MATERIAL").getPath();
        if (map.get(index) != null) {
            map.get(index).forEach(s -> {
                try {
                    List<GenerateMaterialParam> tempList = new ArrayList<>();
                    compositeList.forEach(c -> tempList.add(c));
                    tempList.add(s);
                    generateBufferImages(map, index + 1, tempList, savePath, code);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } else {
            StringBuffer fileName = new StringBuffer("");
            GenerateMaterialParam result = compositeList.get(0);
            fileName.append(result.getMaterialName());
            BufferedImage image = ImageIO.read(new File(materialPrePath + result.getFilePath()));
            for (int i = 1; i < compositeList.size(); i++) {
                GenerateMaterialParam item = compositeList.get(i);
                fileName.append("-" + item.getMaterialName());
                BufferedImage temp = ImageIO.read(new File(materialPrePath + item.getFilePath()));
                BufferedImage bufferedImage = null;
                bufferedImage = overlapImage(image, temp, item.getX(), item.getY());
                image = bufferedImage;
            }
            Records record = new Records();
            String filePath = savePath + fileName.toString() + ".png";
            record.setFilePath(filePath);
            record.setFileName(fileName.toString() + ".png");
            record.setCode(code);
            recordsRepository.save(record);
            ImageIO.write(image, "png", new FileOutputStream(savePath + fileName.toString() + ".png"));
        }
        //return new AsyncResult(null);
    }

    public BufferedImage overlapImage(BufferedImage background, BufferedImage front, int x, int y) {
        try {
            //获取底板
            Graphics2D g = background.createGraphics();
            //在底板上绘制图形
            g.drawImage(front, x, y, front.getWidth(), front.getHeight(), null);
            g.dispose();
            return background;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Map按key进行排序
     *
     * @param map
     * @return
     */
    public Map<Integer, List<GenerateMaterialParam>> sortMapByKey(Map<Integer, List<GenerateMaterialParam>> map) {
        Map<Integer, List<GenerateMaterialParam>> sortMap = new TreeMap<>(new MapKeyComparator());
        sortMap.putAll(map);
        Map<Integer, List<GenerateMaterialParam>> result = new HashMap<>();
        final int[] i = {1};
        sortMap.forEach((k, v) -> {
            result.put(i[0], v);
            i[0] = i[0] + 1;
        });
        return result;
    }

    /**
     * 删除指定文件夹下所有文件
     */
    public boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            temp = new File(path + tempList[i]);
            temp.delete();
        }
        return flag;
    }


}

class MapKeyComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
    }
}
